#!/usr/bin/env python

import gtk
import sys
import os, errno, re
import shutil
import shelve
import tvdb_api
import urllib2
from lxml import etree as ET
import string
import unicodedata
from time import sleep
import thread, threading, gobject
from multiprocessing import Queue

# --- Initialize Threads --- #
gtk.gdk.threads_init()
gobject.threads_init()

# --- Global variables --- #
global buffer_queue
global output_buffer
global version_number

# --- Initializations --- #
version_number = "1.0.5"
buffer_queue = Queue()
output_buffer = gtk.TextBuffer()


#--------------------------------------------#
#-------- Function to Clear Metadata --------#
#--------------------------------------------#
def clear_seasons_metadata_all():
	folder = get_tv_folder()
	season_list = get_all_seasons_folders(folder)

	# Remove series.xml and season jpegs
	for season in season_list:
		seriesxml = folder + "/" + season + "/" + "series.xml"
		if os.path.exists(seriesxml):
			os.remove(seriesxml)
		bannerjpeg = folder + "/" + season + "/" + "banner.jpg"
		if os.path.exists(bannerjpeg):
			os.remove(bannerjpeg)
		folderjpeg = folder + "/" + season + "/" + "folder.jpg"
		if os.path.exists(folderjpeg):
			os.remove(folderjpeg)
		backdropjpeg = folder + "/" + season + "/" + "backdrop.jpg"
		if os.path.exists(backdropjpeg):
			os.remove(backdropjpeg)

#--------------------------------------------#
#-------- Delete All Episode Metada ---------#
#--------------------------------------------#
def clear_all_episode_metadata(show):
	show_folder = get_tv_folder() + "/" + show
	season_list = os.listdir(show_folder)
	for season in season_list:
		metafolder = show_folder + "/" + season  + "/metadata"
		print metafolder
		if os.path.exists(metafolder):
			shutil.rmtree(metafolder)


#--------------------------------------------#
#-------- Get All Season Locations ----------#
#--------------------------------------------#
def get_all_seasons_folders(tv_folder):
	seasons = os.listdir(tv_folder)
	return seasons

# --- Methods to write to buffer --- #
def send_text_to_buffer(text):
	
	# Puts passed in string into the queue
	text = text + "\n"
	buffer_queue.put(text)
	
# --- Regularly retrieve objects from the buffer --- #
def write_to_treeview():
	
	while True: 
		gobject.idle_add(update_treeview)
		sleep(0.01)
	
# --- Writes output from buffer to GUI --- #	
def update_treeview():

	if not buffer_queue.empty():
		text = buffer_queue.get()
		output_buffer.insert_at_cursor(text)
		# Mark position of current last line.
		mk = output_buffer.get_mark("insert")
		# Scroll to mark
		win.textview.scroll_to_mark(mk, 0.0, use_align=True)
		
# --- Get List of Season from File Structure --- #
def get_seasons_list(show_name):
	tv_folder = get_tv_folder()
	path = tv_folder + "/" + show_name
	show_folder_list = os.listdir(path)
	
	seasons_list = []
	for item in show_folder_list:
		if item.startswith("Season"):
			seasons_list.append(item)
			
	return seasons_list

# --- Get Episode List from Season Directory --- #
def get_episode_list(show_name, season):
	
	extension_list = [".avi", ".mp4", ".mp3", "dvr-ms", ".wtv", ".mkv"]
	tv_folder = get_tv_folder()
	path = tv_folder + "/" + show_name + "/" + season
	season_folder_list = os.listdir(path)
	
	episode_list = []
	for item in season_folder_list:
		if os.path.splitext(item)[-1] in extension_list:
			episode_list.append(item) 
	
	return episode_list

# --- Pass Show folder and return list of Seasons --- #
def get_show_folders(tv_show_dir):
	if os.path.exists(tv_show_dir):
		return os.listdir(tv_show_dir)
	else:
		return -1

# --- Retrieves TV directory from database --- #
def get_tv_folder():
	if os.path.exists('meta-TV'):
		db = shelve.open('meta-TV')
		folder = db['tvfolder']
		db.close()
		return folder
	else :
		return -1

# --- Saves TV directory to database --- #
def save_tv_folder(folder):
	db = shelve.open("meta-TV")
	db['tvfolder'] = folder
	db.close()

# --- Returns TVDB show ID from Show Name --- # 
def get_show_id(show_name):
	return tvdb_api.Tvdb()[show_name]['id']

# --- Returns dict of all shows season details --- #
def get_all_episode_details(show_name, season):
	
	season_int = get_season_int(season)
	return tvdb_api.Tvdb()[show_name][season_int]

# --- Creates episode file name from shows details --- #
def format_episode_title(show, season, episode, name, extension):

	sea = str(season)
		
	if int(episode) < 10:
		epi = "0" + str(episode)
	else:
		epi = str(episode)
	
	return show + " - " + sea + "x" + epi + " - " + name + extension


# Creates dict[episode_number] = filename
def get_rename_dict(episodes):
	ep_to_rename_dict = {}
	for episode in episodes:
		epi_num = re.findall('(?<=[EeXx])\d\d',episode)[0]
		ep_to_rename_dict[int(epi_num)] = episode
	
	return ep_to_rename_dict

# Creates dict[episode_number] = episode_title
def get_tvdb_episode_dict(episodes):
	ep_dict = {}
	for i in episodes:
		ep_dict[int(episodes[i]['episodenumber'])] = episodes[i]['episodename']
			
	return ep_dict

# independent of tvdb
def get_season_int(season):
	return int(season[-2:len(season)])

# --- Returns integer episode value from episode title --- #
def get_episode_number(episode):
	return int(re.findall('(?<=[EeXx])\d\d',episode)[0])

# --- Returns extension of file --- #
def get_file_extension(episode):
	return os.path.splitext(episode)[-1]


# --- Creates dict[curr_title] = new_title --- #
def get_new_titles(show, season, cur_epi_title, new_epi_title):
	
	rename_dict = {}
	for i in cur_epi_title.keys():
		rename_dict[cur_epi_title[i]] = new_epi_title[int(i)]
		
	final_dict = {}
	for i in rename_dict:
		episode = get_episode_number(i)
		name = rename_dict[i]
		ext = get_file_extension(i)
		sea = get_season_int(season)
		title = format_episode_title(show, sea, episode, name, ext)
		final_dict[i] = str(title)
	
	return final_dict

# --- Renames show file names --- #
def rename_file(old_file_name, new_file_name, show, season):
	tv_folder = get_tv_folder()
	
	path_to_old = tv_folder + "/" + show + "/" + season + "/" + old_file_name
	path_to_new = tv_folder + "/" + show + "/" + season + "/" + new_file_name
	
	if os.path.exists(path_to_old):
		os.rename(path_to_old, path_to_new)

# --- Extracts shows episode from the title ---#
def extract_episode_from_title(title):
	# Episode title is of the form Show - 9x07 - Title.avi
	# Should return an integer /dx/d/d

	if re.search('x\d\d', title):
		s = re.search('x\d\d', title).group(0)
		return int(s[1:len(s)])
	elif re.search('[Ee]\d\d', title):
		s = re.search('[Ee]\d\d', title).group(0)
		return int(s[1:len(s)])
	else:
		return -1


# --- Creates series.xml file for a show --- #
def create_series_xml(show_name, details):
	path = get_tv_folder() + "/" + show_name + "/" + "series.xml"
	
	nodes = ["id", "Actors", "ContentRating", "FirstAired", "Genre", "IMDbId", "IMDB_ID", 
		"Overview", "Network", "Rating", "Runtime", "SeriesID", "SeriesName", "Status"]
	
	keys = ['id', 'actors', 'contentrating', 'firstaired', 'genre', 'imdb_id', 'imdb_id', 
		'overview', 'network', 'rating', 'runtime', 'seriesid', 'seriesname', 'status']
	
	root = ET.Element('Series')
	
	for i in range(len(nodes)):
		conStr = details[keys[i]]
		ET.SubElement(root, nodes[i]).text = str(conStr).encode('ascii','ignore')
		
	ET.SubElement(root, 'Type').text = "None"
	tree = ET.ElementTree(root)
	tree.write(path, pretty_print=True, xml_declaration=True)


# --- Pass a list of episodes and get their details --- #
def get_episodes_xml_details(list_of_episodes, show_name, season_string):
	
	details = get_all_episode_details(show_name, season_string)
	
	mutex_dict = {}
	for episode in list_of_episodes:
		mutex_dict[episode] = thread.allocate_lock()
		thread.start_new_thread(create_episode_xml
		,(details, episode, show_name,season_string, mutex_dict[episode]))
		
	for episode in list_of_episodes:
		while not mutex_dict[episode].locked():
			sleep(0.1)
		
	send_text_to_buffer("--------------------------------------------")
	send_text_to_buffer(show_name + " episode information update complete.")
	send_text_to_buffer("--------------------------------------------")


# --- Create xml file for a single episode in a season --- #
def create_episode_xml(xml_details, file_name, show_name, season_string, mutex):

	path = get_tv_folder() + "/" + show_name + "/" + season_string + "/metadata"
	if not os.path.exists(path):
		os.makedirs(path)
	
	xml_file_name = os.path.splitext(file_name)[0] + ".xml"
	path_to_xml = path + "/" + xml_file_name
	
	# Get Episode number from file name
	episode_number = extract_episode_from_title(file_name)
	
	# Get the details of a single episode
	#single_episode = get_single_episode(xml_details, episode_number)
	single_episode = xml_details[episode_number]
	
	# Download episode image
	thread.start_new_thread(download_episode_image,(single_episode['filename'], path))
	send_text_to_buffer("Downloading Episode Image " + single_episode['filename'])
	
	nodes = ['ID', 'EpisodeID', 'EpisodeName', 'EpisodeNumber', 'FirstAired', 
		'Overview', 'DVD_chapter', 'DVD_discid', 'DVD_episodenumber', 'DVD_season', 
		'Director', 'GuestStars', 'IMDB_ID', 'Language','ProductionCode', 'Rating', 
		'Writer', 'SeasonNumber', 'absolute_number', 'seasonid', 'seriesid', 'filename']
	
	keys = ['episodenumber', 'id', 'episodename', 'episodenumber', 'firstaired', 
		'overview', 'dvd_chapter', 'dvd_discid', 'dvd_episodenumber', 'dvd_season', 
		'director', 'gueststars', 'imdb_id', 'language', 'productioncode', 'rating', 
		'writer', 'seasonnumber', 'absolute_number', 'seasonid', 'seriesid', 'filename']
	
	root = ET.Element('Item')
	
	for i in range(len(nodes)):
		if nodes[i] == 'filename':
			conStr = "/" + os.path.basename(single_episode[keys[i]])
			ET.SubElement(root, nodes[i]).text = conStr
		else:
			conStr = single_episode[keys[i]]
			ET.SubElement(root, nodes[i]).text = str(conStr).encode('ascii','ignore')
			
	tree = ET.ElementTree(root)
	tree.write(path_to_xml, pretty_print=True, xml_declaration=True)
	
	mutex.acquire()


# --- Downloads the image found at image_url --- #
def download_episode_image(image_url, meta_path):
	image_path = meta_path + "/" + os.path.basename(image_url)
	image = urllib2.urlopen(image_url)
	image_file = open(image_path, 'wb+')
	image_file.write(image.read())
	image_file.close()


# --- Downloads show images (banner, background, folder) --- #
def download_show_images(show, show_info):

	create_series_xml(show, show_info)
	path = get_tv_folder() + "/" + show + "/"

	image_list = ['fanart', 'poster', 'banner']
	win.progress_bar.set_fraction(win.progress_bar.get_fraction() + 0.1)
	
	image_dict = {}
	mutex_dict = {}
	for image in image_list:
		image_dict[image] = show_info[image]
		mutex_dict[image] = thread.allocate_lock()
		
	for image in image_list:
		thread.start_new_thread(download_image, (image_dict[image], path, 
			str(image) + ".jpg", mutex_dict[image]))
		
	for image in image_list:
		while not mutex_dict[image].locked():
			sleep(0.1)
	
	send_text_to_buffer("--------------------------------------------")
	send_text_to_buffer(show + " series information update complete.")
	win.progress_bar.set_text(show + " series information update complete.")
	send_text_to_buffer("--------------------------------------------")
	
	win.load_show_image(show)
	win.progress_bar.set_fraction(1.0)


# ---  Downloads an image --- #
def download_image(full_url, folder, name, mutex):

	if 'fanart' in name:
		name = 'backdrop.jpg'
	elif 'poster' in name:
		name = 'folder.jpg'
	
	path = folder + name
	image = urllib2.urlopen(full_url)
	image_file = open(path, 'wb+')
	image_file.write(image.read())
	image_file.close()
	
	send_text_to_buffer("--------------------------------------------")
	send_text_to_buffer("Downloaded " + name + " to " + folder)
	win.progress_bar.set_text("Downloaded " + name + " to " + folder)
	send_text_to_buffer("--------------------------------------------")
	
	win.progress_bar.set_fraction(win.progress_bar.get_fraction() + 0.25)
	
	mutex.acquire()	

# --- Class for UI  --- #
class MyUiWindow:
	
	# Downloads series.xml file and show images
	def on_series_info_button_clicked(self, widget):
		self.progress_bar.set_fraction(0.0)
		# Gets currently selected show
		model, i =  self.show_tree_selection.get_tree_view().get_selection().get_selected()
		
		# If Show is selected, get show title from liststore
		if i is not None:
			show = self.liststore.get_value(i,0)

			self.progress_bar.set_fraction(self.progress_bar.get_fraction() + 0.1)
			show_details = tvdb_api.Tvdb()[show]			
			
			thread.start_new_thread(download_show_images, (show, show_details))
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("Updating " + show + " series information.")
			self.progress_bar.set_text("Updating " + show + " series information.")
			send_text_to_buffer("--------------------------------------------")
			
		else:
			# Output error message to buffer
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("No Show Selected")	
			send_text_to_buffer("--------------------------------------------")
			
	def on_ep_cancel_clicked(self, widget):
		# Hide Episodes window
		self.episodes.hide()
		
	def on_ep_ok_clicked(self, widget):
		# Hide episodes window
		self.episodes.hide()
		
	def on_episode_check_toggled(self, widget, path, model):
		# Toggles check box when clicked
		model[path][1] = not model[path][1]
		
	def on_select_all_epi_clicked(self, widget):
		for item in self.episodestore:
			item[1] = True

	def get_checked_episodes(self):
		# Returns a list of checked episodes
		episode_list = []
		
		# If check-box column in liststore is
		# true add episode to episode_list
		for item in self.episodestore:
			if item[1]:
				episode_list.append(item[0])
		
		return episode_list
	
	def on_get_meta_clicked(self, widget):
		# episode_list, show_name, season_string
		# get episode xml
		# name xml - Show - SSxEE - Title.xml
		# save in Season
		# download screen-shot
		
		episode_list = self.get_checked_episodes()
		show = self.get_selected_show() #strings
		season = self.get_selected_season() #string
		
		if len(episode_list) > 0:
			thread.start_new_thread(get_episodes_xml_details,(episode_list, show,
			 season))
		else:
			send_text_to_buffer("No Episodes Selected")
		
		self.on_season_clicked(self.season_tree_selection)	
		
	def on_episode_rename_clicked(self, widget):
		
		epi_to_rename = self.get_checked_episodes()
		rename_dict = get_rename_dict(epi_to_rename)
			
		# Get show, season, and show ID for TVDB
		show = self.get_selected_show() #strings
		season = self.get_selected_season() #strings
		ID = get_show_id(show) 
		
		# Get All the episodes from a particular season from TVDB
		all_episodes = get_all_episode_details(show, season)
		
		# Get dictionary of all episodes from tvdb
		tvdb_episode_dict = get_tvdb_episode_dict(all_episodes)
		
		# Get dictionary with old file names as keys and new file names
		change_dict = get_new_titles(show, season, rename_dict, tvdb_episode_dict)
		
		for key in change_dict.keys():
			builder = gtk.Builder()
			builder.add_from_file("pfetchy.glade")
			self.renamedialog = builder.get_object("renamedialog")
			self.curr_name_label = builder.get_object("curr_name_label")
			self.new_title_entry = builder.get_object("new_title_entry")
			self.curr_name_label.set_text(key)
			
			change_dict[key] = change_dict[key].replace("/", "-")
			self.new_title_entry.set_text(change_dict[key])
			builder.connect_signals(self)
			self.renamedialog.run()
			
		self.on_season_clicked(self.season_tree_selection)
		
	def on_clear_all_show_metadata_activate(self, widget):
		clear_seasons_metadata_all()

	def on_rename_yes_clicked(self, widget):
	
		show = self.get_selected_show()
		season = self.get_selected_season()
		old = self.curr_name_label.get_text()
		new = self.new_title_entry.get_text()
		
		rename_file(old, new, show, season)
		
		
		self.curr_name_label.destroy()
		self.new_title_entry.destroy()
		self.renamedialog.destroy()
		
	def on_rename_no_clicked(self, widget):
		self.curr_name_label.destroy()
		self.new_title_entry.destroy()
		self.renamedialog.destroy()
		
	
	def get_selected_show(self):
		model, item = self.show_tree_view.get_selection().get_selected()
		show = self.liststore.get_value(item,0)
		return show
		
	def get_selected_season(self):
		model, item = self.season_tree_view.get_selection().get_selected()
		season = self.seasonstore.get_value(item,0)
		return season
			
	
	def on_treeview_row_activated(self, treeview, i, col):
		self.seasonstore.clear()
		show = self.get_selected_show()
		
		seasons_list = get_seasons_list(show)
		
		send_text_to_buffer("--------------------------------------------")
		send_text_to_buffer("Show: " + show + " loaded.")
		send_text_to_buffer("--------------------------------------------")
		send_text_to_buffer("Loading... ")
		for season in seasons_list:
			self.seasonstore.append([season])
			send_text_to_buffer(season)
		send_text_to_buffer("--------------------------------------------")
		
		
		self.episodes.show()
		
	
	def on_show_clicked(self, tree_selection):
		self.seasonstore.clear()
		model, i = tree_selection.get_tree_view().get_selection().get_selected()
		if i is not None:
			show = self.liststore.get_value(i,0)
			self.load_show_image(show)
			
	def on_season_clicked(self, tree_selection):
		self.episodestore.clear()
		sh_model, sh_i = self.show_tree_selection.get_tree_view().get_selection().get_selected()
		if sh_i is not None:
			show = self.liststore.get_value(sh_i,0)
		else:
			show = -1
	
		model, i = tree_selection.get_tree_view().get_selection().get_selected()
		if i is not None:
			season = self.seasonstore.get_value(i,0)
		else:
			season = -1
			
		if show is not -1 and season is not -1 :
			episode_list = get_episode_list(show, season)
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("Season: " + season + " loaded.")
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("Loading... ")
			for episode in episode_list:
				self.episodestore.append([episode, False])
				send_text_to_buffer(episode)
			send_text_to_buffer("--------------------------------------------")
	
	
	def get_pixbuf_from_image(self, image):
		path = "images/" + image
		print path
		
		if os.path.exists(path):
			pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, 64, 64)
			return pixbuf
		else:
			return None
		
	def load_show_image(self, show):
		if get_tv_folder() > 0:
			path_to_image = get_tv_folder() + "/" + show + "/" + "folder.jpg"
			path_to_banner = get_tv_folder() + "/" + show + "/" + "banner.jpg"
		else:
			path_to_image = "/" + show + "/" + "folder.jpg"
			path_to_banner = "/" + show + "/" + "banner.jpg"
			
		pfetchy_folder = "images/pfetchyfolder.jpg"
		pfetchy_banner = "images/pfetchybanner.jpg"
		
		if os.path.exists(path_to_image):
			self.show_pix = gtk.gdk.pixbuf_new_from_file_at_size(path_to_image, 191
			, 280)
		else:
			self.show_pix = gtk.gdk.pixbuf_new_from_file_at_size(pfetchy_folder, 191
			, 280)
		
		self.show_image.set_from_pixbuf(self.show_pix)
			
		if os.path.exists(path_to_banner):
			self.banner_pix = gtk.gdk.pixbuf_new_from_file_at_size(path_to_banner,
			 700,130)
		else:
			self.banner_pix = gtk.gdk.pixbuf_new_from_file_at_size(pfetchy_banner,
			700,130)
		self.banner_image.set_from_pixbuf(self.banner_pix)
	
	def on_window_destroy(self, widget, data=None):
		gtk.main_quit()
		
	def on_tv_folder_button_clicked(self, widget, data=None):
		# Choose TV Folder using FileChooser with select folder action
		# set.
		chooser = gtk.FileChooserDialog(title="Choose Folder", parent=None,
		action= gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, 
		buttons= (gtk.STOCK_OK, gtk.RESPONSE_OK))
		
		# Run chooser window and collect response.
		response = chooser.run()
		
		# Sets folder to selected Folder when OK is clicked.
		# Destroy chooser.
		if response == gtk.RESPONSE_OK:
			folder = chooser.get_filename()
			chooser.destroy()
			
		# Sets text entry to selected Folder
		self.tv_folder_entry.set_text(folder)
		
		
	def on_pref_ok_clicked(self, widget, data=None):
		# When OK is clicked folder in text entry 
		# is stored in folder
		folder = self.tv_folder_entry.get_text()
		
		# Folder is store in db
		save_tv_folder(folder)
		
		# Load TV folder contents into Show list
		self.load_tv_shows(folder)
		
		# Load default pfetchy images
		self.load_show_image("")
		
		# Hide preference window
		self.preferences.hide()
		
	def on_pref_cancel_clicked(self, widget, data=None):
		# Cancel out of preferences without saving changes.
		
		# Fetches folder stored in db and loads into entry.
		self.tv_folder_entry.set_text(get_tv_folder())
		
		# Hide preference window
		self.preferences.hide()
		
	def load_db(self):
		# Gets TV folder location from db
		folder = get_tv_folder()
		
		# If db is not empty load tv shows into Show list
		# If db is empty out-put message
		if folder is not -1:
			self.load_tv_shows(folder)
		else :
			send_text_to_buffer( "--------------------------------------------")
			send_text_to_buffer("TV Folder not set")
			send_text_to_buffer("--------------------------------------------")
	
	def load_tv_shows(self, folder):
		# Clear current Show list by clearing liststore
		self.liststore.clear()
		
		# Get list of show folders in TV folder
		shows = get_show_folders(folder)
		
		# If TV folder does not contain shows or TV folder is not set
		if shows == -1:
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("TV folder does not contain")
			send_text_to_buffer("shows or TV folder not set.")
			send_text_to_buffer("--------------------------------------------")
		else:
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("TV Folder set to: ")
			send_text_to_buffer(folder)
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("--------------------------------------------")
			send_text_to_buffer("Loaded Shows: ")
			
			# Else load shows into liststore and output confirmation message
			for show in shows:
				self.liststore.append([show])
				send_text_to_buffer(show)
			send_text_to_buffer("--------------------------------------------")
	
	def on_open_pref_activate(self, parent):
		# Check if TV folder has been set, if true then set text_entry to
		# folder location. Else set entry to empty string
		if get_tv_folder() > 0:
			self.tv_folder_entry.set_text(get_tv_folder())
		else:
			self.tv_folder_entry.set_text("")
		
		# Show preference window
		self.preferences.show()
		
	def on_about_menu_item_activate(self, parent):
		# Run about dialog and wait for reponse
		self.aboutdialog.run()
		
		# Destroy about dialog when close button is pressed.
		self.aboutdialog.hide()
		
		
	def __init__(self):
		builder = gtk.Builder()
		builder.add_from_file("pfetchy.glade")
		self.window = builder.get_object("window")
		self.preferences = builder.get_object("preference")
		self.episodes = builder.get_object("episodes")
		self.aboutdialog = builder.get_object("pfetchy_about")
		
		self.tv_folder_entry = builder.get_object("tv_folder_entry")
		self.textview = builder.get_object("textview")
		self.show_tree_view = builder.get_object("treeview")
		self.show_tree_selection = self.show_tree_view.get_selection()
		self.season_tree_view = builder.get_object("season_tree_view")
		self.season_tree_selection = self.season_tree_view.get_selection()
		self.episode_tree_view = builder.get_object("episode_tree_view")
		self.episode_tree_selection = self.episode_tree_view.get_selection()
		
		self.liststore = builder.get_object("liststore")
		self.seasonstore = builder.get_object("season_store")
		self.episodestore = builder.get_object("episode_store")
		self.checkbox = builder.get_object("episode_check")
		
		self.show_image = builder.get_object("show_image")
		self.banner_image = builder.get_object("banner_image")
		self.progress_bar = builder.get_object("progress_bar")
		
		
		self.textview.set_buffer(output_buffer)
		self.textview.set_property("editable", False)
		builder.connect_signals(self)
		self.show_tree_selection.connect("changed", self.on_show_clicked)
		self.season_tree_selection.connect("changed", self.on_season_clicked)
		self.checkbox.connect("toggled", self.on_episode_check_toggled,
		self.episodestore)
		
	def main(self):
		self.load_show_image("")
		self.window.set_title("pfetchy " + version_number)
		self.window.set_icon(self.get_pixbuf_from_image("pfetchylogo.svg"))
		self.window.show()
		send_text_to_buffer("--------------------------------------------")
		send_text_to_buffer("pfetchy Version " + version_number)
		self.window.show()
		thread.start_new_thread(write_to_treeview,())
		self.load_db()
		#gtk.threads_enter()
 		gtk.main()
 		#gtk.threads_leave()

if __name__ == '__main__':
	win = MyUiWindow()
	win.main()
